/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package com.inspur.edp.metadata.rtcustomization.core;

import com.inspur.edp.lcm.metadata.api.entity.GspMetadata;
import com.inspur.edp.lcm.metadata.api.entity.Metadata4Ref;
import com.inspur.edp.lcm.metadata.api.entity.MetadataHeader;
import com.inspur.edp.lcm.metadata.api.entity.ServiceUnitInfo;
import com.inspur.edp.lcm.metadata.cache.MetadataCacheManager;
import com.inspur.edp.lcm.metadata.cache.MetadataRtDistCache;
import com.inspur.edp.metadata.rtcustomization.api.CustomizationRtService;
import com.inspur.edp.metadata.rtcustomization.api.entity.*;
import com.inspur.edp.metadata.rtcustomization.api.exception.ErrorCodes;
import com.inspur.edp.metadata.rtcustomization.api.exception.LcmMetadataException;
import com.inspur.edp.metadata.rtcustomization.common.EnvironmentContext;
import com.inspur.edp.metadata.rtcustomization.core.async.UpdateMetadataCacheRunnable;
import com.inspur.edp.metadata.rtcustomization.core.manager.RpcManager;
import io.iec.edp.caf.commons.utils.SpringBeanUtils;
import io.iec.edp.caf.rpc.api.service.RpcClient;
import io.iec.edp.caf.rpc.api.support.Type;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.io.File;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;

@Slf4j
public class CustomizationRtServiceImp extends AbstractMetadataService implements CustomizationRtService {
    @Override
    public List<Metadata4Ref> getAllCustomizedRtMetadataInfo(List<String> metadataTypes) {
        String types = "";
        if (metadataTypes != null && metadataTypes.size() > 0) {
            for (String metadataType : metadataTypes) {
                types += metadataType + ",";
            }
            types.substring(0, types.length() - 1);
        }
        RpcClient client = SpringBeanUtils.getBean(RpcClient.class);
        LinkedHashMap<String, Object> params = new LinkedHashMap<>();
        params.put("metadataTypes", types);
        Type<List> type = new Type<>(List.class, Metadata4Ref.class);
        try {
            return client.invoke(type, "com.inspur.edp.metadata.rtcustomization.serverapi.CustomizationRtServerService.getAllCustomizedRtMetadataInfoWithTypes", "Lcm", params, null);
        } catch (Exception e) {
            throw new LcmMetadataException(e, ErrorCodes.ECP_METADATA_0002, "com.inspur.edp.metadata.rtcustomization.serverapi.CustomizationRtServerService.getAllCustomizedRtMetadataInfoWithTypes");
        }
    }

    @Override
    public List<DimensionExtendEntity> getExtMdByBasicMdId(String metadataId, String certId) {
        if (StringUtils.isEmpty(metadataId)) {
            throw new LcmMetadataException(ErrorCodes.ECP_METADATA_0003, "metadataId");
        }
        RpcClient client = SpringBeanUtils.getBean(RpcClient.class);
        LinkedHashMap<String, Object> params = new LinkedHashMap<>();
        params.put("metadataId", metadataId);
        params.put("certId", certId);
        Type<List> type = new Type<>(List.class, DimensionExtendEntity.class);
        try {
            return client.invoke(type, "com.inspur.edp.metadata.rtcustomization.serverapi.CustomizationRtServerService.getExtMdByBasicMdId", "Lcm", params, null);
        } catch (Exception e) {
            throw new LcmMetadataException(e, ErrorCodes.ECP_METADATA_0002, "com.inspur.edp.metadata.rtcustomization.serverapi.CustomizationRtServerService.getExtMdByBasicMdId");
        }
    }

    @Override
    public void preloadMetadata(MetadataFilter metadataFilter) {
        RpcManager<Object> rpcManager = new RpcManager<>(new Type<>(Object.class), "com.inspur.edp.metadata.rtcustomization.serverapi.CustomizationRtServerService.preloadMetadata");
        rpcManager.getParams().put("metadataFilter", metadataFilter);
        rpcManager.invoke();
    }

    @Override
    public List<Metadata4Ref> getMetadataListByFilters(List<MetadataFilter> metadataFilters) {
        RpcManager<List> rpcManager = new RpcManager<>(new Type<>(List.class, Metadata4Ref.class), "com.inspur.edp.metadata.rtcustomization.serverapi.CustomizationRtServerService.getMetadataListByFilters");
        rpcManager.getParams().put("metadataFilters", metadataFilters);
        return rpcManager.invoke();
    }

    @Override
    public List<Metadata4Ref> getMetadataListByFilter(MetadataFilter metadataFilter) {
        return getMetadataListByFilters(Arrays.asList(metadataFilter));
    }

    @Override
    public void saveMdpkg(File mdpkg) {
        RpcManager<Object> rpcManager = new RpcManager<>(new Type<>(Object.class), "com.inspur.edp.metadata.rtcustomization.serverapi.CustomizationRtServerService.saveMdpkg");
        rpcManager.getParams().put("mdpkg", mdpkg);
        rpcManager.invoke();
    }

    @Override
    public ServiceUnitInfo getServiceUnitInfo(String metadataId) {
        ServiceUnitInfo serviceUnitInfo = (ServiceUnitInfo) MetadataCacheManager.getServiceUnitInfo(metadataId);
        if (serviceUnitInfo != null) {
            return serviceUnitInfo;
        }

        RpcManager<ServiceUnitInfo> rpcManager = new RpcManager<>(new Type<>(ServiceUnitInfo.class), "com.inspur.edp.metadata.rtcustomization.serverapi.CustomizationRtServerService.getServiceUnitInfo");
        rpcManager.getParams().put("metadataId", metadataId);
        return rpcManager.invoke();
    }

    @Override
    public void removeCacheByMetadataIds(List<String> metadataIds) {
        if (CollectionUtils.isEmpty(metadataIds)) {
            return;
        }
        RpcClient client = SpringBeanUtils.getBean(RpcClient.class);
        LinkedHashMap<String, Object> params = new LinkedHashMap<>();
        params.put("metadataIds", metadataIds);
        try {
            client.invoke(void.class, "com.inspur.edp.metadata.rtcustomization.serverapi.CustomizationRtServerService.removeCacheByMetadataIds", "Lcm", params, null);
        } catch (Exception e) {
            throw new LcmMetadataException(e, ErrorCodes.ECP_METADATA_0002, "com.inspur.edp.metadata.rtcustomization.serverapi.CustomizationRtServerService.removeCacheByMetadataIds");
        }
    }

    @Override
    public List<MetadataHeader> getMetadatasByRefedMetadataId(String metadataId) {
        RpcManager<List> rpcManager = new RpcManager<>(new Type<>(List.class, MetadataHeader.class), "com.inspur.edp.metadata.rtcustomization.serverapi.CustomizationRtServerService.getMetadatasByRefedMetadataId");
        rpcManager.getParams().put("metadataId", metadataId);
        return rpcManager.invoke();
    }

    @Override
    public List<MetadataHeader> getMetadatasByRefedMetadataId(String metadataId, List<String> metadataTypes) {
        RpcManager<List> rpcManager = new RpcManager<>(new Type<>(List.class, MetadataHeader.class), "com.inspur.edp.metadata.rtcustomization.serverapi.CustomizationRtServerService.getMetadatasByRefedMetadataIdAndMetadataTypes");
        rpcManager.getParams().put("metadataId", metadataId);
        rpcManager.getParams().put("metadataTypes", metadataTypes);
        return rpcManager.invoke();
    }

    @Override
    public Metadata4Ref getMetadata4RefWithSourceType(String metadataId) {
        if (!StringUtils.hasLength(metadataId)) {
            throw new LcmMetadataException(ErrorCodes.ECP_METADATA_0003, "metadataId");
        }
        RpcManager<Metadata4Ref> rpcManager = new RpcManager<>(new Type<>(Metadata4Ref.class), "com.inspur.edp.metadata.rtcustomization.serverapi.CustomizationRtServerService.getMetadata4RefWithSourceType");
        rpcManager.getParams().put("metadataId", metadataId);
        return rpcManager.invoke();
    }

    @Override
    protected GspMetadata getMetadataFromCache(String metadataId, boolean isI18n) {
        // 如果缓存模式是调试模式，则不用缓存
        if (EnvironmentContext.cacheMode == CacheModeEnum.debug) {
            return null;
        }
        GspMetadata metadata = MetadataRtDistCache.get(metadataId, isI18n);
        if (metadata != null && metadata.getContent() == null) {
            log.error("从缓存中获取的元数据不为空，但是元数据内容为空：" + metadataId);
            log.error("堆栈信息如下：" + Arrays.toString(Thread.currentThread().getStackTrace()));
            return null;
        }
        return metadata;
    }

    @Override
    public MetadataStringDto invokeRpc(RpcClient client, LinkedHashMap<String, Object> params) {
        try {
            return client.invoke(MetadataStringDto.class, "com.inspur.edp.metadata.rtcustomization.serverapi.CustomizationRtServerService.getMetadataStringDto", "Lcm", params, null);
        } catch (Exception e) {
            throw new LcmMetadataException(e, ErrorCodes.ECP_METADATA_0002, "com.inspur.edp.metadata.rtcustomization.serverapi.CustomizationRtServerService.getMetadataStringDto");
        }
    }

    @Override
    protected void asyncUpdateCache(GspMetadata metadata, boolean isI18n) {
        UpdateMetadataCacheRunnable updateMetadataCacheRunnable = new UpdateMetadataCacheRunnable(MetadataScopeEnum.RUNTIME, isI18n, metadata);
        new Thread(updateMetadataCacheRunnable).start();
    }

    @Override
    public ChangeMetadataSourceTypeResponse changeMetadataSourceType(List<ChangeMetadataSourceTypeInfo> changeInfos) {
        RpcClient client = SpringBeanUtils.getBean(RpcClient.class);
        LinkedHashMap<String, Object> params = new LinkedHashMap<>();
        params.put("changeInfos", changeInfos);
        try {
            return client.invoke(ChangeMetadataSourceTypeResponse.class, "com.inspur.edp.metadata.rtcustomization.serverapi.CustomizationRtServerService.changeMetadataSourceType", "Lcm", params, null);
        } catch (Exception e) {
            throw new LcmMetadataException(e, ErrorCodes.ECP_METADATA_0002, "com.inspur.edp.metadata.rtcustomization.serverapi.CustomizationRtServerService.changeMetadataSourceType");
        }
    }
}
